// wgltexture.cpp
//

#include "config.h"
#include "wgl/wgltexture.hpp"
#include "wgl/wgl_gl.hpp"

#include "stb/stb_image.h"

using namespace wgl;



// Texture::~Texture
//
Texture::~Texture ()
{
  if (image)
    stbi_image_free(image);
}



// Texture::load
//
void Texture::load ( const std::string &path )
{
  WGL_ASSERT(!image);
  
  int w, h;
  int nchans = 4;
  WGL_TRACE("loading texture '%s'", path.c_str());
  if (!(image = stbi_load(path.c_str(), &w, &h, &nchans, 4)))
    WGL_FATAL("could not load texture: '%s'", path.c_str());

  width = size_t(w);
  height = size_t(h);
  
  WGL_TRACE(" -> %lux%lux%d", WGL_LU(width), WGL_LU(height), nchans);
}



// Texture::upload
//
GLuint Texture::upload ()
{
  WGL_ASSERT(image);
  WGL_ASSERT(glid == 0);

  gl.GenTextures(1, &glid);
  gl.BindTexture(GL_TEXTURE_2D, glid);
  
  gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

  gl.TexImage2D(GL_TEXTURE_2D,
                0,
                GL_RGBA,
                width,
                height,
                0,
                GL_RGBA,
                GL_UNSIGNED_BYTE,
                image);

  return glid;
}
